package com.aaa.sso.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ FileName: CustomModularRealmAuthenticator
 * @ Description:
 * @ Author:  STB
 * @ CreateTime: 2025/9/5 0005 9:51
 * @ Version: 1.0.0
 */
public class CustomModularRealmAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        //判断有没有realm被配置，如果没有直接抛异常 IllegalStateException  代码终止运行
        this.assertRealmsConfigured();
        //强转转换,真正使用时，肯定使用我们自定义的，所以强转
        CustomUsernamePasswordToken customUsernamePasswordToken = (CustomUsernamePasswordToken) authenticationToken;
        //获取realm
        Collection<Realm> realms = this.getRealms();
        //定义realm集合
        List<Realm> customRealmList = new ArrayList<>();
        //循环遍历
        for (Realm realm : realms) {
            //获取当前realm的名字 MemberRealm ,UserRealm
            String realmName = realm.getName();
            //判断  customUsernamePasswordToken.getLoginType()=  User 或者 Member
            if (realmName.contains(customUsernamePasswordToken.getLoginType())) {
                //匹配上的加入自定realm集合
                customRealmList.add(realm);
            }
        }
        return customRealmList.size() == 1 ? this.doSingleRealmAuthentication((Realm) customRealmList.iterator().next(),
                customUsernamePasswordToken) :
                this.doMultiRealmAuthentication(customRealmList,
                        customUsernamePasswordToken);
    }
}
